package com.gblfy.lyrabbitmq.utils;

import com.gblfy.lyrabbitmq.confirms.ConfirmCallBackListener;
import com.gblfy.lyrabbitmq.consts.MQPrefixConst;
import com.gblfy.lyrabbitmq.returns.ReturnCallBackListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * MQ发送消息(公用工具类)
 *
 * @author gblfy
 * @Date 2021-09-28 9:59
 */
@Component
public class MQSendMsgUtils {

    private final static Logger log = LoggerFactory.getLogger(MQSendMsgUtils.class);

    @Autowired//注入发送消息模板
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ConfirmCallBackListener confirmCallback;
    @Autowired
    private ReturnCallBackListener returnCallback;

    /**
     * 发送MQ STRING类型消息 第1种
     *
     * @param queueRouteKey 路由routingKey
     * @param msg           MQ STRING类型消息
     */
    public void snedStrMQMsg(String queueRouteKey, String msg) {
        try {
            log.info("交换机名称: {}, 路由routingKey: {}, 发送的消息: {} ", "EXCHANGE-CMIIP", queueRouteKey, msg);
            String mID = UUID.randomUUID().toString();
            CorrelationData correlationId = new CorrelationData(mID);

            // Confirm 消息确认策略
            rabbitTemplate.setConfirmCallback(confirmCallback);
            // Return 消息确认策略
            rabbitTemplate.setReturnCallback(returnCallback);
            log.info("发送消息的路由key: {}", queueRouteKey);
            log.info("发送消息的标识ID: {}", mID);

            //发送消息到MQ的交换机，通知其他系统
            rabbitTemplate.convertAndSend(MQPrefixConst.WS_EXCEHANGE, queueRouteKey, msg, correlationId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
